<template>
  <div>
    <el-card>
      <div class="wrap">
        <el-input class="input" placeholder="用户名" size="mini" v-model="searchKey" />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchFn">查询</el-button>
        <el-button size="mini">清空</el-button>
      </div>
      <el-button type="primary" size="mini" @click="dialogVisible1 = true">添加</el-button>
      <button class="btn">批量删除</button>
      <el-table :data="userlist" style="width: 100%" border v-loading="loading">
        <el-table-column width="40" type="selection"> </el-table-column>
        <el-table-column label="序号" width="60" type="index" align="center"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
        <el-table-column prop="roleName" label="角色列表"> </el-table-column>
        <el-table-column prop="gmtCreate" label="创建事件"> </el-table-column>
        <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="{ row }">
            <el-button type="info" size="mini" class="button" @click="setUser(row)"
              ><i class="el-icon-user-solid icon"></i
            ></el-button>
            <el-button type="primary" size="mini" class="button" @click="editUser(row)"
              ><i class="el-icon-edit-outline icon"></i
            ></el-button>

            <el-button type="danger" size="mini" class="button" @click="deleteUser(row.id)"
              ><i class="el-icon-delete icon"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15]"
        :page-size="limit"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      >
      </el-pagination>
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible1"
        width="50%"
        :before-close="handleClose"
        top
      >
        <el-form label-width="120px" :model="addUserForm" :rules="addUserRules" ref="addUserDom">
          <el-form-item label="用户名" size="mini" prop="username">
            <el-input v-model="addUserForm.username" />
          </el-form-item>
          <el-form-item label="用户昵称" size="mini" prop="nickName">
            <el-input v-model="addUserForm.nickName" />
          </el-form-item>
          <el-form-item label="用户密码" size="mini" prop="password">
            <el-input type="password" v-model="addUserForm.password" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="设置角色"
        :visible.sync="dialogVisible2"
        width="50%"
        :before-close="handleClose"
        top
      >
        <el-form label-width="120px">
          <el-form-item label="用户名" size="mini">
            <el-input :value="setUserForm.username" disabled />
          </el-form-item>
          <el-form-item size="mini" label="角色列表">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in cities" :label="city" :key="city">{{ city }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="setUserConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改用户"
        :visible.sync="dialogVisible3"
        width="50%"
        :before-close="handleClose"
        top
      >
        <el-form
          label-width="120px"
          :rules="changeUserRules"
          :model="changeUser"
          ref="changeUserDom"
        >
          <el-form-item label="用户名" size="mini" prop="username">
            <el-input v-model="changeUser.username" />
          </el-form-item>
          <el-form-item label="用户昵称" size="mini"  prop="nickName">
            <el-input v-model="changeUser.nickName" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取 消</el-button>
          <el-button type="primary" @click="changeUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { reqUserRoles } from '@/api/role'
import { reqUserList, reqAddUser, reqUserInfoUpdate, reqUserRemove, reqDoAssign } from '@/api/user'


export default {
  name: 'User',
  data() {
    return {
      page: 1,
      limit: 5,
      userlist: [],
      userlist2: [],
      total: 10,
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      loading: false,
      addUserForm: {
        nickName: '',
        password: '',
        username: ''
      },
      addUserRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      setUserForm: {
        username: '',
        rules: []
      },
      checkAll: false,
      checkedCities: [],
      cities: [],
      //是否显示全选框的横线
      isIndeterminate: true,
      roleList: [],
      roleId: '',
      changeUser: {
        username: '',
        nickName: ''
      },
      changeUserRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      },
      searchKey:''
    }
  },
  mounted() {
    this.request()
    this.reqRoles()
  },
  methods: {
  async  searchFn(){
      const result2 = await reqUserList(1, 100)
      this.userlist2= result2.data.items
      this.userlist=  this.userlist2.filter(item=>{
          return item.username.includes(this.searchKey)||item.nickName.includes(this.searchKey);

      })
    this.page=1
    this.limit=100
    },
    async request() {
      this.loading = true
      const { page, limit } = this
      const result = await reqUserList(page, limit)
      this.userlist = result.data.items

      this.total = result.data.total
      this.loading = false
    },
    handleSizeChange(val) {
      this.limit = val
      this.request()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.page = val
      this.request()
      console.log(`当前页: ${val}`)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    async addUserConfirm() {
      try {
        if (this.addUserForm.username == 'admin') {
          this.$message.error('不能添加用户名admin哦')
          return
        }
        await this.$refs.addUserDom.validate()
        await reqAddUser(this.addUserForm)
        this.$message.success('添加用户成功!!!')
        this.request()
        this.dialogVisible1 = false
      } catch (error) {}
    },
    async setUser(row) {
      this.roleId = row.id
      this.checkedCities = row.roleName.split(',')
      this.setUserForm.username = row.username
      this.dialogVisible2 = true
    },
    //分配角色
    async setUserConfirm() {
      this.dialogVisible2 = false
      var idList = []
      this.checkedCities.map(item => {
        this.roleList.forEach(obj => {
          if (obj.roleName == item) {
            idList.push(obj.id)
          }
        })
      })
      var idList2 = idList.join(',')
      console.log(this.roleId, idList2)
      await reqDoAssign(this.roleId, idList2)
      this.$message.success('分配角色成功!!')
      this.request()
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    },
    async reqRoles() {
      const result = await reqUserRoles(1, 20)
      this.roleList = result.data.items
      this.cities = result.data.items.map(item => {
        return item.roleName
      })
    },
    editUser(row) {
      this.roleId=row.id
      this.dialogVisible3 = true
      this.changeUser.username=row.username
      this.changeUser.nickName=row.nickName
    },
   async changeUserInfo(){
    try{
      await this.$refs.changeUserDom.validate()
      const id=this.roleId
      const {username,nickName}=this.changeUser
      console.log(id,username,nickName)
     await reqUserInfoUpdate({id,username,nickName})
      this.$message.success('修改用户信息成功!!')
      this.dialogVisible3 = false
      this.request()

    }catch(error){

    }


    },
    async deleteUser(id){
      try{
        await reqUserRemove(id)
        this.$message.success('删除用户成功!!')
        this.request()
      }catch(error){

      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  display: flex;
  margin-bottom: 30px;
}
.input {
  width: 150px;
  margin-right: 10px;
}
.btn {
  color: white;
  margin-left: 10px;
  border: none;
  width: 80px;
  height: 28px;
  border-radius: 3px;
  background-color: pink;
  font-size: 14px;
  transform: translateY(1px);
  margin-bottom: 20px;
}
.btn:hover {
  background-color: rgb(232, 171, 181);
}
.pagination {
  margin-top: 20px;
}
</style>
